//
//  UIApplication +Visible.swift
//  HomeFurnishing
//
//  Created by 智蚂优服 on 2019/1/4.
//  Copyright © 2019 智蚂优服. All rights reserved.
//

import Foundation
import UIKit
import Toast_Swift

extension UIApplication : ZMCompatible{}
extension ZM where Base : UIApplication {
    /// 找到当前显示的window
    public static func getCurrentWindow() -> UIWindow? {
        var window: UIWindow? = UIApplication.shared.keyWindow
        if window?.windowLevel != UIWindow.Level.normal{
             let windows = UIApplication.shared.windows
             for windowTemp in windows {
                if windowTemp.windowLevel == UIWindow.Level.normal {
                 window = windowTemp
                 break
             }
           }
         }
        return window
    }
    
    /// 获取当前控制器
    public static func visibleViewController() -> UIViewController {
        return self.getVisibleViewControllerFrom(viewController: self.getCurrentWindow()?.rootViewController)!
    }
    
    /// 获取当前导航控制器
    public static func visibleNavigationController() -> UINavigationController {
        return self.visibleViewController().navigationController ?? ((UIApplication.shared.keyWindow?.rootViewController as! UITabBarController).selectedViewController as! UINavigationController)
    }
    
    public static func getVisibleViewControllerFrom(viewController: UIViewController?) -> UIViewController? {
        if viewController == nil {
            return nil
        }
        if viewController!.isKind(of: UINavigationController.self) {
            return self.getVisibleViewControllerFrom(viewController: (viewController as! UINavigationController).visibleViewController)
        }else if viewController!.isKind(of: UITabBarController.self) {
            return self.getVisibleViewControllerFrom(viewController: (viewController as! UITabBarController).selectedViewController)
        }else if ((viewController?.presentedViewController) != nil){
            return self.getVisibleViewControllerFrom(viewController: viewController?.presentedViewController!)
        }else{
            return viewController
        }
    }
}
